import axios, { AxiosInstance } from 'axios';
import { IMyRequestConfig } from './type';
import { isStringType } from '@/utils';
export default class MyRequest {
  instance: AxiosInstance;
  constructor(config: IMyRequestConfig) {
    this.instance = axios.create(config);
    const { interceptors, needGlobalInterceptors = true } = config;
    // 添加自定义请求过滤
    if (interceptors) {
      const { request, requestError, response, responseError } = interceptors;
      this.instance.interceptors.request.use(request, requestError);
      this.instance.interceptors.response.use(response, responseError);
    }
    // 是否添加全局过滤器
    if (needGlobalInterceptors) {
      this.instance.interceptors.request.use(
        (config) => {
          return config;
        },
        (error) => {
          return error;
        }
      );
      this.instance.interceptors.response.use(
        (response) => {
          return response.data;
        },
        (error) => {
          return error;
        }
      );
    }
  }
  request<T = unknown>(config: IMyRequestConfig<T>): Promise<T> {
    // 每个请求独立的过滤器
    if (config?.interceptors?.request) {
      config = config?.interceptors?.request(config);
    }
    return this.instance
      .request<T>(config)
      .then((res) => {
        if (config.interceptors?.response) {
          const result = config.interceptors.response(res.data);
          return result;
        }
        return res.data;
      })
      .catch((error) => {
        console.log(
          '%c 🍎 接口请求出错: ',
          'font-size:20px;background-color: #4b4b4b;color:#fff;',
          error
        );
        return error;
      })
      .finally(() => {
        // TODO:loading重置
      });
  }
  get<T>(url: string, params?: any): Promise<T>;
  get<T>(config: IMyRequestConfig<T>): Promise<T>;
  get<T>(arg1: IMyRequestConfig<T> | string, params?: any) {
    if (isStringType(arg1)) {
      return this.request({ url: arg1, params });
    }
    return this.request({ ...arg1, method: 'GET' });
  }
}
